package com.ftg.learn.aop;

import com.ftg.learn.entity.SysLog;
import com.ftg.learn.mapper.SysLogMapper;
import lombok.SneakyThrows;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Enumeration;

/**
 * aop来完成对日志的管理
 *  切面类
 * @author kangjx
 * @version 1.0
 * @date 2023/3/31 上午10:07
 */
@Aspect
@Component
public class LogManagerAop {

    private final Log log = LogFactory.getLog(LogManagerAop.class);


    //配置目标类里面哪一个方法(切点)
//    @Pointcut("execution(public * com.ftg.learn.service.impl.*.*(..) )")
//    private void outWorkd(){}

//    @Before("execution(public * com.ftg.learn.service.impl.*.*(..) )")
//    private void outWorkd1(){
//        System.out.println("我在你之前Before");
//    }
//
//    @After("execution(public * com.ftg.learn.service.impl.*.*(..) )")
//    private void outWorkd2(){
//        System.out.println("我在你之后Before");
//    }

    @Resource
    HttpServletRequest req;

    @Resource
    SysLogMapper sysLogMapper;

    @Around("execution(public * com.ftg.learn.service.impl.*.*(..) )")
    private Object outWorkd2(ProceedingJoinPoint p){
        Object returnVal = null;
        SysLog sysLog = new SysLog();
        sysLog.setIpaddress(req.getRemoteAddr());
        sysLog.setMacaddress(req.getRemoteHost());
        sysLog.setMethodname(p.getTarget().getClass().getName());
//
//        System.out.println(p.getThis().getClass().getName());
//
//        System.out.println(p.getSignature().getName());
//        System.out.println(req.getLocalAddr());
//
//        Enumeration<String> headerNames = req.getHeaderNames();
//
//        while(headerNames.hasMoreElements()){
//            String headName = headerNames.nextElement();
//            System.out.println("名称为" + headName +"值为:"+req.getHeader(headName));
//        }

        try {
            returnVal = p.proceed();
            sysLog.setDesc("成功");
        } catch (Throwable e) {
            sysLog.setDesc("失败");
            log.error("err-10096 方法调用失败",e);
        }

        sysLogMapper.saveSysLog(sysLog);
        return returnVal;
    }

}
